package com.czk.bootlettuce.servcie.impl;

import com.czk.bootlettuce.pojo.User;
import com.czk.bootlettuce.servcie.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/8/3 23:43
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    /**
     * 注入对象
     */
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 对redis模板操作string类型的对象进行简化
     */
    @Resource(name = "redisTemplate")
    private ValueOperations<String,String> stringValueOperations;
    /**
     * 对redis模板操作hash类型的对象进行简化
     */
    @Resource(name = "redisTemplate")
    private HashOperations<String, String, User> hashOperations;
    /**
     * redisTemplate操作String类型
     * @param key
     * @return
     */
    @Override
    public String getString(String key) {

        // redisTemplate操作数据类型
        if (redisTemplate.hasKey(key)){
            // 存在
            log.info("在redis中查找");
            String s = stringValueOperations.get(key);
            return s;
        }else {
            // 在数据库中取
            log.info("在数据库中取值");
            String value="czk";
            // 存储到redis中
            redisTemplate.opsForValue().set(key,value);
            return value;
        }
    }

    @Override
    public void expire(String key, String value) {
        // 存储
        redisTemplate.opsForValue().set(key,value);
        // 设置过期时间
        redisTemplate.expire(key,30, TimeUnit.SECONDS);
    }

    /**
     * redisTemplate操作hash类型
     * @param id
     * @return
     */
    @Override
    public User selectById(String id){
        if (redisTemplate.opsForHash().hasKey("user",id)){
            // redis存在
            log.info("在redis中取");
            User user = hashOperations.get("user", id);
            return user;
        }else {
            // 数据库查询
            log.info("在数据库中查询");
            User user=new User(id,"czk",25);
            // 存在redis中
            log.info("存入redis");
            redisTemplate.opsForHash().put("user",id,user);
            return user;
        }
    }
}
